package com.bwie.agent.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;


import com.bwie.agent.config.ExcelUtil;
import com.bwie.common.utils.CreateImageCode;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.bwie.agent.entity.UserEntity;
import com.bwie.agent.service.UserService;
import com.bwie.common.utils.PageUtils;
import com.bwie.common.utils.R;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 
 *
 * @author lfw
 * @email sunlightcs@gmail.com
 * @date 2022-03-24 16:17:42
 */
@RestController
@RequestMapping("agent/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 发送短信
     */
    @RequestMapping("/sendmsg")
    public R list(@RequestParam(value = "tel") String tel){
        rabbitTemplate.convertAndSend("06a",tel);
        return R.ok();
    }

    /**
     * 获取验证码
     */
    @RequestMapping("/getImage")
    public R getImage() throws IOException {
        CreateImageCode createImageCode = new CreateImageCode();
        //获取验证码
        String securityCode = createImageCode.getCode();
        //验证码存入session
        String key = new SimpleDateFormat("yyyyMMdd").format(new Date());
        //生成图片
        BufferedImage image = createImageCode.getBuffImg();
        //进行base64编码
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", bos);
        String string = Base64Utils.encodeToString(bos.toByteArray());
        return R.ok().put("key",key).put("image",string).put("securityCode",securityCode);
    }


    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = userService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 登录
     */
    @RequestMapping("/login")
    public R login(@RequestBody UserEntity user){
        R login = userService.login(user);
        return login;
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{userId}")
    public R info(@PathVariable("userId") Integer userId){
		UserEntity user = userService.getById(userId);

        return R.ok().put("user", user);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody UserEntity user){
        R r=userService.register(user);
        return r;
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody UserEntity user){
		userService.updateById(user);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] userIds){
		userService.removeByIds(Arrays.asList(userIds));

        return R.ok();
    }

    /**
     * 导出报表
     *
     * @return
     */
    @RequestMapping(value = "/export")
    public void export(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取数据
        List<UserEntity> list = userService.list();

        //excel标题
        String[] title = {"用户id", "用户名", "密码", "真实姓名","电子邮箱","联系电话","备注","冻结状态 1活跃 2注销"};

        //excel文件名
        String fileName = "用户信息表" + System.currentTimeMillis() + ".xls";

        //sheet名
        String sheetName = "用户信息表";

        String [][] content = new String[list.size()][8];

        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            UserEntity obj = list.get(i);
            content[i][0] = obj.getUserId().toString();
            content[i][1] = obj.getUserNikeName();
            content[i][2] = obj.getUserPwd();
            content[i][3] = obj.getUserName();
            content[i][4] = obj.getUserEmail();
            content[i][5] = obj.getUserTel();
            content[i][6] = obj.getUserMaibox();
            content[i][7] = obj.getUserStatus();
        }

        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);

        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送响应流方法
     */
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}
